<!DOCTYPE html>
<html>
<head>
    <title>Realtime Map</title>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="https://unpkg.com/leaflet/dist/leaflet.css" />
    <style>
        #map { height: 100vh; }
    </style>
</head>
<body>
    <div id="map"></div>
    <script src="https://unpkg.com/leaflet/dist/leaflet.js"></script>
    <script src="https://cdn.socket.io/4.0.0/socket.io.min.js"></script>
    <script>
        var map = L.map('map').setView([39.900, 119.600], 15);
        L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
            maxZoom: 19,
        }).addTo(map);

        var insMarker = L.marker([39.900, 119.600]).addTo(map);
        var lightMarker = L.marker([39.894583, 119.631400]).addTo(map);
        var triangleLayer = L.polygon([]).addTo(map);
        var targetMarkers = []; // Array to store target markers

        var socket = io.connect('http://' + document.domain + ':' + location.port);

        socket.on('ins_data', function(data) {
            console.log("Received ins_data:", data);
            insMarker.setLatLng([data.lat, data.lon]);
            var triangle = drawTriangle(data.lat, data.lon, data.direction);
            triangleLayer.setLatLngs(triangle);
            map.setView([data.lat, data.lon], map.getZoom());
        });

        socket.on('target_data', function(data) {
            console.log("Received target_data:", data);
            // Clear existing target markers
            targetMarkers.forEach(function(marker) {
                map.removeLayer(marker);
            });
            targetMarkers = [];

            // Update INS marker and light marker
            insMarker.setLatLng([data.ins_lat, data.ins_lon]);
            lightMarker.setLatLng([data.light_lat, data.light_lon]);
            var triangle = drawTriangle(data.ins_lat, data.ins_lon, data.direction);
            triangleLayer.setLatLngs(triangle);
            map.setView([data.ins_lat, data.ins_lon], map.getZoom());

            // Add new target markers
            data.targets.forEach(function(target) {
                var marker = L.marker([target.lat, target.lon]);
                marker.addTo(map);
                targetMarkers.push(marker);
            });
        });

        function drawTriangle(lat, lon, direction) {
            var size = 0.001; // Increase the length of the triangle
            var width = 0.0002; // Width of the triangle
            var p1 = [lat + size * Math.cos(direction * Math.PI / 180), lon + size * Math.sin(direction * Math.PI / 180)];
            var p2 = [lat + width * Math.cos((direction + 135) * Math.PI / 180), lon + width * Math.sin((direction + 135) * Math.PI / 180)];
            var p3 = [lat + width * Math.cos((direction - 135) * Math.PI / 180), lon + width * Math.sin((direction - 135) * Math.PI / 180)];
            return [p1, p2, p3];
        }
    </script>
</body>
</html>
